<?php
namespace App\Admin\Controllers\File;

use App\Func\UploadFile;
use App\Models\File\FileProfitLT;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class LTProfitUploadController extends AdminController{

    protected $title = '乐天月报文件上传';

    protected function grid()
    {
        return view("file.profit-lt.index");
    }

    public function upload(Request $request){
        $files = $request->file('source_file');
        if(!$files){
            return response()->json(['status' => false, 'message' => '请先上传文件！']);
        }
        if(count($files) > 1){
            return response()->json(['status' => false, 'message' => '上传文件不能超过1个！']);
        }
        $param = $request->get('param');
        try{
            $fileDate = $param['file_date'];
            $fileType = $param['file_type'];
            $fail = [];
            $userId = Admin::user()->id;
            DB::beginTransaction();
            foreach ($files as $k => $file){
                if ($file->isValid()) {
                    $fileName = $file->getClientOriginalName();
                    if(filesize($file) > 35 * 1024 * 1024){
                        $fail[$k] = $fileName.'文件过大！';
                        continue;
                    }
                    $fs = FileProfitLT::query()->firstOrNew([
                        'file_date' => $fileDate,
                        'file_type' => $fileType,
                        'file_name' => $fileName,
                    ]);
                    if(!$fs){
                        $fail[$k] = $fileName.'文件添加失败！';
                        continue;
                    }
                    if($fs->user_id){//有人已经上传，无需再上传
                        continue;
                    }
                    $fs->user_id = $userId;
                    $flag1 = $fs->save();
                    if(!$flag1){
                        $fail[$k] = $fileName.'文件添加失败！';
                        continue;
                    }
                    $uf = UploadFile::getInit();
                    $_fileDir = FileProfitLT::fileDir(strtotime($fileDate));
                    $_fileName = FileProfitLT::fileName($fileType,$userId,$fileName);
                    $flag2 = $uf->upload($file,$_fileDir,false,$_fileName);
                    if(!$flag2){
                        $fail[$k] = $fileName.'文件上传失败！';
                        continue;
                    }
                }
            }
            DB::commit();
            if(count($fail) > 0){
                return response()->json(['status' => false, 'message' => implode(PHP_EOL,$fail)]);
            }else{
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }
}
